<template>
  <div class="AcceptAndHearACase" v-loading="loading">
    <el-form :inline="true" :model="searchData">
      <el-form-item label="账号状态：">
        <el-select v-model="searchData.status" placeholder="请选择状态">
          <el-option label="启用" :value="1"></el-option>
          <el-option label="禁用" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权限分类：">
        <el-select v-model="searchData.purview" placeholder="请选择权限">
          <el-option label="管理员" :value="1"></el-option>
          <el-option label="普通用户" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="账号：">
        <el-input
          v-model="searchData.account"
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="serach"
          class="btn-search"
          >筛选</el-button
        >
        <el-button icon="el-icon-refresh-left" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="newBuilt"
      class="btn-export"
      >添加用户信息</el-button
    >
    <el-table
      :data="tableData"
      style="width: 100%"
      height="84%"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" align="center">
      </el-table-column>
      <el-table-column prop="disable" label="账号状态" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.disable === 0 ? "禁用" : "启用" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="headImg">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.headImg" style="width: 150px; height: 150px" />
            <img
              slot="reference"
              :src="scope.row.headImg"
              style="max-height: 80px; max-width: 80px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center">
      </el-table-column>
      <el-table-column prop="username" label="账号" align="center">
      </el-table-column>
      <el-table-column prop="type" label="权限" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type ? "管理员" : "普通用户" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="用户名" align="center">
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" align="center">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button
            @click="handleClick(scope.row)"
            type="text"
            size="medium"
            style="margin-right: 10px"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除吗？"
            @confirm="deleteConfirm(scope.row)"
          >
            <el-button
              slot="reference"
              type="text"
              size="medium"
              style="color: red"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="AcceptAndHearACase-content-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="isNew ? '新建' : '编辑'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      v-loading="loading"
    >
      <el-form
        :model="formData"
        label-width="100px"
        :rules="formRules"
        ref="form"
      >
        <el-form-item label="头像：" prop="headImg">
          <el-upload
            class="avatar-uploader"
            action="http://43.139.235.169:8081/cos/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.headImg"
              :src="formData.headImg"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="账号状态：" prop="disable">
          <el-radio-group v-model="formData.disable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号：" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入账号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone" v-if="isNew">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="账号权限：" prop="type">
          <el-select v-model="formData.type" placeholder="请选择账号权限">
            <el-option label="管理员" :value="1"></el-option>
            <el-option label="普通用户" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="formData.password"
            placeholder="请输入密码"
            type="password"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名：" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    const validateHeadImg = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请上传头像"));
      } else {
        callback();
      }
    };
    const validateDisable = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请选择账号状态"));
      } else {
        callback();
      }
    };
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    const validateType = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请选择账号权限"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (
        !/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/.test(
          value
        )
      ) {
        callback(new Error("请输入正确手机号"));
      } else {
        callback();
      }
    };
    return {
      //加载状态
      loading: false,
      //分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchData: {
        status: "",
        purview: "",
        account: "",
      },
      tableData: [],
      dialogVisible: false,
      formData: {},
      //储存密码以判断是否有更改密码
      savePassword: "",
      //弹窗校验规则
      isNew: false,
      formRules: {
        headImg: [
          { required: true, trigger: "blur", validator: validateHeadImg },
        ],
        disable: [
          { required: true, trigger: "change", validator: validateDisable },
        ],
        username: [
          { required: true, trigger: "change", validator: validateUsername },
        ],
        type: [{ required: true, trigger: "change", validator: validateType }],
        password: [
          { required: true, trigger: "change", validator: validatePassword },
        ],
        name: [{ required: true, trigger: "change", validator: validateName }],
        phone: [
          { required: true, trigger: "change", validator: validatePhone },
        ],
      },
    };
  },
  mounted() {
    this.userListPaging();
  },
  methods: {
    //获取数据
    async userListPaging(disable, type, username) {
      this.loading = true;
      const res = await this.$api.userListPaging({
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        disable: disable, //账号状态
        type: type, //权限分类
        username: username, //账号
      });
      // console.log(res.data);
      this.tableData = res.data.records;
      this.total = res.data.total;
      this.loading = false;
    },
    //查询数据
    serach() {
      this.userListPaging(
        this.searchData.status,
        this.searchData.purview,
        this.searchData.account
      );
    },
    //重置按钮
    reset() {
      this.searchData = {
        purview: "",
        status: "",
        account: "",
      };
      this.userListPaging();
    },
    //新建
    newBuilt() {
      this.formData = {
        headImg: "",
      };
      this.isNew = true;
      this.dialogVisible = true;
    },
    //编辑
    handleClick(row) {
      // console.log(row);
      this.savePassword = row.password;
      this.formData = row;
      this.isNew = false;
      this.dialogVisible = true;
    },
    //编辑或者新建弹窗确认
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.isNew) {
            //新建
            this.$api
              .userAddOrUpdate({
                headImg: this.formData.headImg,
                disable: this.formData.disable,
                type: this.formData.type,
                userType: this.formData.type,
                username: this.formData.username,
                password: this.formData.password,
                phone: this.formData.phone,
                name: this.formData.name,
              })
              .then((res) => {
                if (res.code === 0) {
                  this.loading = false;
                  this.dialogVisible = false;
                  this.reset();
                  this.$message({
                    message: "新建成功！",
                    type: "success",
                  });
                }
              });
          } else {
            //编辑
            let password;
            if (this.savePassword == this.formData.password) {
              password = null;
            } else {
              password = this.formData.password;
            }
            this.$api
              .userAddOrUpdate({
                id: this.formData.id,
                headImg: this.formData.headImg,
                disable: this.formData.disable,
                type: this.formData.type,
                userType: this.formData.type,
                username: this.formData.username,
                password: password,
                name: this.formData.name,
              })
              .then((res) => {
                // console.log(res);
                if (res.code === 0) {
                  this.loading = false;
                  this.dialogVisible = false;
                  this.reset();
                  this.$message({
                    message: "修改成功！",
                    type: "success",
                  });
                }
              });
          }
        } else {
          this.$message({
            message: "请输入完整内容",
            type: "error",
          });
          return;
        }
      });
    },
    //关闭弹窗的方法
    handleClose() {
      this.dialogVisible = false;
    },
    //上传成功
    handleAvatarSuccess(res, file) {
      this.formData.headImg = res.resultObj;
      this.loading = false;
      //移除头像表单校验结果
      this.$refs.form.clearValidate("headImg");
    },
    //上传前
    beforeAvatarUpload(file) {
      this.loading = true;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      this.loading = isJPG && isLt2M;
      return isJPG && isLt2M;
    },
    //删除
    async deleteConfirm(row) {
      const res = await this.$api.deleteById({
        id: row.id,
      });
      if (res.code === 0) {
        this.serach();
        this.$message({
          message: "删除成功！",
          type: "success",
        });
      }
    },
    //页数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      let that = this;
      that.pageSize = val;
      that.serach();
    },
    //翻页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      let that = this;
      that.currentPage = val;
      that.serach();
    },
  },
};
</script>

<style lang="scss" scoped>
.btn-search {
  background: #409eff;
  border: 1px solid #409eff;
  &:hover {
    opacity: 0.8;
  }
}
.btn-export {
  width: 140px;
  background: #409eff;
  border: 1px solid #409eff;
  margin-bottom: 20px;
  &:hover {
    opacity: 0.8;
  }
}
.avatar-uploader ::v-deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep(.el-upload):hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.AcceptAndHearACase {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #ffffff;
  border-radius: 4px;
  padding: 24px;
  overflow: hidden;

  &-content {
    width: 100%;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    &-table {
      width: 100%;
      flex: 1;
      overflow-y: auto;
    }
    &-page {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      margin-top: 16px;
      .el-pagination {
        padding: 0;
        .el-pagination__total {
          line-height: 40px;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.8);
        }
      }
    }
  }
}
</style>

